package Hxw3DEngine.core.controller
{
	import Hxw3DEngine.error.ErrorType;
	import Hxw3DEngine.proxy.Stage3DProxy;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3DRenderMode;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	public class ViewBase3D extends Sprite
	{
		
		public var stage3d:Stage3D;
		
		public var camera:Camera3D;
		
		public var scene:Scene3D;
		
		public function ViewBase3D()
		{
			if(stage){
				init();
			}else{
				addEventListener(Event.ADDED_TO_STAGE,init);
			}
		}
		
		private function init(e:Event = null):void{
			
			camera = new Camera3D;
			scene = new Scene3D;
			scene.camera = camera;
			
			if(hasEventListener(Event.ADDED_TO_STAGE)){
				removeEventListener(Event.ADDED_TO_STAGE,init);
			}
			
			if(stage.stage3Ds.length){
				stage.scaleMode = StageScaleMode.NO_SCALE;
				stage.align = StageAlign.TOP_LEFT;
				stage3d = stage.stage3Ds[0];
				stage3d.addEventListener(Event.CONTEXT3D_CREATE,onCreatComplete);
				stage3d.addEventListener(ErrorEvent.ERROR,onCreatError);
				stage3d.requestContext3D(Context3DRenderMode.AUTO);
				stage.addEventListener(Event.RESIZE,drawBackground);
			}else{
				throw new Error(ErrorType.NOTSUPPORT3D);
			}
		}
		
		private function onCreatError(e:ErrorEvent):void{
			throw new Error(ErrorType.NOTSUPPORT3D);
		}
		
		private function onCreatComplete(e:Event):void{
			Stage3DProxy.insdance.context3d = e.target.context3D;
			Stage3DProxy.insdance.stage = stage;
			Stage3DProxy.insdance.camera = camera;
			drawBackground();
			addEventListener(Event.ENTER_FRAME,function ():void{startRender()});
			startRender();
		}
		
		public function drawBackground(e:Event = null):void {
			if(Stage3DProxy.context3d != null){
				Stage3DProxy.context3d.configureBackBuffer(stage.stageWidth, stage.stageHeight, 0);
			}
		}
		
		public function startRender():void{
			scene.render();
		}
		
		
	}
}